package com.ruoyi.mq

import cn.hutool.core.util.StrUtil
import cn.hutool.json.JSONUtil
import com.ruoyi.app.common.HuoshanApi
import com.ruoyi.back.domain.UserRecord
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class UserRecordApiFunc {

    private val log: Logger = LoggerFactory.getLogger(UserRecordApiFunc::class.java)

    @Autowired
    private lateinit var changeFaceExtendService: ChangeFaceExtendService

    @Autowired
    private lateinit var changeFaceTaskManager: ChangeFaceTaskManager

    @Autowired
    private lateinit var hsApi: HuoshanApi

    /**
     * 参数校验
     */
    fun check(userRecord: UserRecord): Boolean = userRecord.run {

        if (StrUtil.isBlank(requestId)) {
            log.info("视频换脸发生异常 请求无效")
            changeFaceExtendService.error(this, null, "请求无效!")
            return true
        }
        return false
    }


    /**
     * 火山请求
     */
    fun hs(userRecord: UserRecord) = userRecord.run {

        try {
            log.info("开始解析火山api请求, requestId -> $requestId")
            hsApi.videoSwapResult(requestId!!)
                .let { faceFusionMovieGetResultData ->
                    log.info("当前处理结果是 ${faceFusionMovieGetResultData.data.respData}")
                    when (faceFusionMovieGetResultData.data.status) {
                        "done" -> {
                            changeFaceExtendService.success(
                                this,
                                JSONUtil.parseObj(faceFusionMovieGetResultData.data.respData),
                                2
                            )
                            log.info("当前requestId: $requestId 执行火山api完毕")
                        }

                        "not_found" -> changeFaceExtendService.error(this, null, "资源找不到!")
                        else -> changeFaceTaskManager.doing(this)
                    }
                }
        } catch (e: Exception) {
            changeFaceExtendService.error(this, null, e.message)

        }
    }

    /**
     * 阿里api
     */
    fun ali(userRecord: UserRecord, json: String) = userRecord.run {
        log.info("开始解析阿里云api请求, requestId -> $requestId")
        JSONUtil.parseObj(json).also { log.info("当前处理结果是 $it") }.let { data ->
            data.getStr("Status").let { status ->
                when (status) {
                    "PROCESS_SUCCESS" -> {
                        changeFaceExtendService.success(this, data.getJSONObject("Result"), 1)
                        log.info("当前requestId: $requestId 执行阿里云api完毕")
                    }

                    "PROCESS_FAILED", "TIMEOUT_FAILED", "LIMIT_RETRY_FAILED" -> {
                        changeFaceExtendService.error(this, data, null)
                    }

                    else -> changeFaceTaskManager.doing(this)
                }
            }
        }
    }
}